package com.eazy.lkv2.web.controller.mobile.activity;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.eazy.lkv2.core.Global;
import com.eazy.lkv2.core.util.QrUtil;
import com.eazy.lkv2.web.entity.ActivityUser;
import com.eazy.lkv2.web.entity.Activitys;
import com.eazy.lkv2.web.entity.User;
import com.eazy.lkv2.web.service.activity.ActivityService;
import com.eazy.lkv2.web.service.activity.ActivityUserService;
import com.eazy.lkv2.web.service.system.SystemUserService;
import com.eazy.lkv2.web.vo.JsonResponse;
import com.eazy.lkv2.web.vo.SignUpVO;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.udf.UDFFinder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import com.eazy.lkv2.web.controller.BaseController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import java.io.File;
import java.util.List;

/**
 * @author ywj
 * @date 2016.9.8
 * @desc 手机端活动列表
 */
@Controller
@RequestMapping("/mobileActivity")
public class MobileActivityController extends BaseController<Object, Integer> {

    @Autowired
    private ActivityService activityService;

    @Autowired
    private ActivityUserService activityUserService;

    @Autowired
    private SystemUserService systemUserService;

    @RequestMapping(value = "newactivitys.html", method = RequestMethod.GET)
    public String activitys(Model model) {
        model.addAttribute("activityData", activityService.select());
        return getDefault("activity/activitys");
    }

    @RequestMapping(value = "/details.html/{id}", method = RequestMethod.GET)
    public String activitysDetail(@PathVariable("id") String id, Model model) {
        Activitys activity = activityService.findById(Integer.parseInt(id));
        model.addAttribute("activity", activity);
        return "mobile/activity/activity_detail";
    }

    @RequestMapping(value = "event/{id}", method = RequestMethod.GET)
    public String event(@PathVariable("id") String id,Model model) {
        Cookie[] cookies=getRequest().getCookies();
        if(cookies.length>0){
            for(Cookie cookie:cookies){
                if(cookie.getName().equals("userId")){
                    logger.debug("load userId cookie:"+cookie.getValue());
                    String userId=cookie.getValue();
                    if(StringUtils.isNotEmpty(userId)){
                        model.addAttribute("userId", cookie.getValue());
                    }
                }
            }
        }
        Activitys activity = activityService.findById(Integer.parseInt(id));
        int userCount=activityUserService.selectUserCountByActivityId(Integer.parseInt(id));
        model.addAttribute("activity", activity);
        model.addAttribute("userCount", userCount);
        return getDefault("activity/event");
    }
    /**
     * 跳转报名页
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value = "event/{id}/user{userId}", method = RequestMethod.GET)
    public String event(@PathVariable("id") String id, @PathVariable("userId") String userId,Model model) {
        Activitys activity = activityService.findById(Integer.parseInt(id));
        int userCount=activityUserService.selectUserCountByActivityId(Integer.parseInt(id));
        model.addAttribute("activity", activity);
        model.addAttribute("userCount", userCount);
        model.addAttribute("userId", userId);
        return getDefault("activity/event");
    }
    /**
     * 跳转报名页
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value = "toSignUp/{id}", method = RequestMethod.GET)
    public String toSignUp(@PathVariable("id") String id, @RequestParam(value = "userId",required = false)String userId,Model model) {
        if(StringUtils.isNotEmpty(userId)){
            model.addAttribute("user",systemUserService.findById(userId));
            ActivityUser activityUser=new ActivityUser();
            activityUser.setSignIn(1);
            activityUser.setActivityId(Integer.parseInt(id));
            activityUser.setUserId(Integer.parseInt(userId));
            List<ActivityUser>list=activityUserService.queryByObject(activityUser);
            activityUser=list.get(0);
            model.addAttribute("auId",activityUser.getId());
        }
        Activitys activity = activityService.findById(Integer.parseInt(id));
        model.addAttribute("activity", activity);
        return getDefault("activity/signUp");
    }



    /**
     * 活动报名
     * @param signUpVO
     * @return
     */
    @RequestMapping(value = "signUp", method = RequestMethod.POST)
    public String signUp(SignUpVO signUpVO,Model model) {
        int userId=0;
//        if(userId==0){
            User user = new User();
            user.setName(signUpVO.getUserName().trim());
            user.setPhone(signUpVO.getMobile());
            List<User> list = systemUserService.queryByObject(user);
            if (null == list || list.size() == 0) {
                systemUserService.create(user);
                userId=user.getId();
            } else {
                userId = list.get(0).getId();
            }
//        }
        ActivityUser activityUser = new ActivityUser();

        if(signUpVO.getAuId()!=null){
            activityUser=activityUserService.findById(signUpVO.getAuId());
            activityUser.setUserId(userId);
            activityUserService.update(activityUser);
        }else{
            activityUser.setActivityId(signUpVO.getActivityId());
            activityUser.setActivityName(signUpVO.getActivityName());
            activityUser.setUserId(userId);
            activityUser.setSignUp(1);
            activityUser.setSignIn(0);
            String aid = String.valueOf(signUpVO.getActivityId());
            List<ActivityUser>list1=activityUserService.queryByObject(activityUser);
            if(list1==null||list1.size()==0){
                String fix = "0";
                if (aid.length() < 2) {
                    fix = "000";
                } else if (aid.length() < 3) {
                    fix = "00";
                }else if (aid.length() < 4){
                    fix="0";
                }
                String code = aid + fix + generateSixNumer();
                activityUser.setActivityCode(code);
                activityUserService.create(activityUser);
            }else{
                activityUser.setId(list1.get(0).getId());
                activityUserService.update(activityUser);
            }

        }
        Cookie cookie = new Cookie("userId",String.valueOf(userId));
        cookie.setMaxAge(0);
        getResponse().addCookie(cookie);
        logger.debug("clear userId cookie:");
        model.addAttribute("activityUser", activityUser);
        return getDefault("activity/signup_succeed");
    }

    /**
     * 取消报名
     * @param id
     */
    @RequestMapping(value = "cancelJoin/{id}", method = RequestMethod.POST)
    public void signUpCancel(@PathVariable("id") String id) {
        ActivityUser activityUser = activityUserService.findById(Integer.parseInt(id));
        int activityId = activityUser.getActivityId();
        boolean result = activityUserService.removeById(Integer.parseInt(id));
        JsonResponse response = new JsonResponse();
        response.code = result ? 200 : 500;
        response.msg = result ? "" : "取消失败";
        Cookie cookie = new Cookie("userId","");
        cookie.setMaxAge(60 * 60 * 24*365);
        getResponse().addCookie(cookie);
        renderJson(response);
    }

    private int generateSixNumer() {
        int intFlag = (int) (Math.random() * 1000000);
        String flag = String.valueOf(intFlag);
        if (flag.length() == 6 && flag.substring(0, 1).equals("9")) {
            return intFlag;
        } else {
            return intFlag + 100000;
        }
    }


    @RequestMapping(value = "toJoinDetail/{id}/user{userId}", method = RequestMethod.GET)
    public String toJoin(@PathVariable("id") String id, @PathVariable("userId") String userId, Model model) {

        ActivityUser activityUser = new ActivityUser();
        activityUser.setActivityId(Integer.parseInt(id));
        activityUser.setUserId(Integer.parseInt(userId));
        activityUser.setSignUp(1);
        List<ActivityUser> list = activityUserService.queryByObject(activityUser);
        if (list != null && list.size() > 0) {
            activityUser = list.get(0);
        } else {
            Activitys activity = activityService.findById(Integer.parseInt(id));
            int userCount=activityUserService.selectUserCountByActivityId(Integer.parseInt(id));
            model.addAttribute("activity", activity);
            model.addAttribute("userCount", userCount);
            model.addAttribute("userId", null);
            Cookie cookie = new Cookie("userId","");
            cookie.setMaxAge(60 * 60 * 24*365);
            getResponse().addCookie(cookie);
            return getDefault("activity/event");
        }
        User user = systemUserService.findById(userId);
        model.addAttribute("activityUser", activityUser);
        model.addAttribute("userInfo", user);
        return getDefault("activity/JoinActivityDetail");
    }



    @RequestMapping(value = "GetActivityUserList")
    public void getUserList(@RequestParam(value = "activityId")String activityId){
        List<User>userList=activityUserService.selectUserListByActivityId(Integer.parseInt(activityId));
        JSONObject jsonObject=new JSONObject();
        JSONArray jsonArray=new JSONArray(userList.size());
        for(User user:userList){
            JSONObject object=new JSONObject();
            object.put("name",user.getName());
            object.put("HeadImgurl",user.getIcon());
            jsonArray.add(object);
        }
        jsonObject.put("list",jsonArray);
        renderJson(jsonObject.toJSONString());
    }

}
